/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2023/9/15 23:09:53
 *        Description: 暂无
 ***********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Caching.AccressToken;
using CoreCms.Net.Configuration;
using CoreCms.Net.DTO.WeChatShipping;
using CoreCms.Net.IRepository;
using CoreCms.Net.IRepository.UnitOfWork;
using CoreCms.Net.IServices;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.ViewModels.Api;
using CoreCms.Net.Model.ViewModels.Basics;
using CoreCms.Net.Model.ViewModels.UI;
using CoreCms.Net.WeChat.Service.HttpClients;
using Flurl.Http;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using SqlSugar;


namespace CoreCms.Net.Services
{
    /// <summary>
    /// 微信发货快递公司信息 接口实现
    /// </summary>
    public class WeChatShippingDeliveryServices : BaseServices<WeChatShippingDelivery>, IWeChatShippingDeliveryServices
    {
        private readonly IWeChatShippingDeliveryRepository _dal;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IWeChatApiHttpClientFactory _weChatApiHttpClientFactory;


        public WeChatShippingDeliveryServices(IUnitOfWork unitOfWork, IWeChatShippingDeliveryRepository dal, IWeChatApiHttpClientFactory weChatApiHttpClientFactory)
        {
            this._dal = dal;
            _weChatApiHttpClientFactory = weChatApiHttpClientFactory;
            base.BaseDal = dal;
            _unitOfWork = unitOfWork;
        }

        #region 实现重写增删改查操作==========================================================

        /// <summary>
        /// 重写异步插入方法
        /// </summary>
        /// <param name="entity">实体数据</param>
        /// <returns></returns>
        public async Task<AdminUiCallBack> InsertAsync(WeChatShippingDelivery entity)
        {
            return await _dal.InsertAsync(entity);
        }

        /// <summary>
        /// 重写异步更新方法方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<AdminUiCallBack> UpdateAsync(WeChatShippingDelivery entity)
        {
            return await _dal.UpdateAsync(entity);
        }

        /// <summary>
        /// 重写异步更新方法方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<AdminUiCallBack> UpdateAsync(List<WeChatShippingDelivery> entity)
        {
            return await _dal.UpdateAsync(entity);
        }

        /// <summary>
        /// 重写删除指定ID的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<AdminUiCallBack> DeleteByIdAsync(object id)
        {
            return await _dal.DeleteByIdAsync(id);
        }

        /// <summary>
        /// 重写删除指定ID集合的数据(批量删除)
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<AdminUiCallBack> DeleteByIdsAsync(int[] ids)
        {
            return await _dal.DeleteByIdsAsync(ids);
        }

        #endregion

        #region 获取缓存的所有数据==========================================================

        /// <summary>
        /// 获取缓存的所有数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<WeChatShippingDelivery>> GetCaChe()
        {
            return await _dal.GetCaChe();
        }

        #endregion

        #region 重写根据条件查询分页数据
        /// <summary>
        ///     重写根据条件查询分页数据
        /// </summary>
        /// <param name="predicate">判断集合</param>
        /// <param name="orderByType">排序方式</param>
        /// <param name="pageIndex">当前页面索引</param>
        /// <param name="pageSize">分布大小</param>
        /// <param name="orderByExpression"></param>
        /// <param name="blUseNoLock">是否使用WITH(NOLOCK)</param>
        /// <returns></returns>
        public async Task<IPageList<WeChatShippingDelivery>> QueryPageAsync(Expression<Func<WeChatShippingDelivery, bool>> predicate,
            Expression<Func<WeChatShippingDelivery, object>> orderByExpression, OrderByType orderByType, int pageIndex = 1,
            int pageSize = 20, bool blUseNoLock = false)
        {
            return await _dal.QueryPageAsync(predicate, orderByExpression, orderByType, pageIndex, pageSize, blUseNoLock);
        }
        #endregion


        /// <summary>
        /// 通过接口更新所有快递公司信息
        /// </summary>
        public async Task<AdminUiCallBack> DoUpdateCompany()
        {
            var jm = new AdminUiCallBack();

            var accessToken = WeChatCacheAccessTokenHelper.GetWxOpenAccessToken();

            var url = $"https://api.weixin.qq.com/cgi-bin/express/delivery/open_msg/get_delivery_list?access_token={accessToken}";

            var postData = new { accessToken };

            var result = await url.PostJsonAsync(postData).ReceiveJson<GetDeliveryListResult>();

            var bl = result != null;

            if (result is { errcode: 0 })
            {
                //先清空历史表
                await _dal.DeleteAsync(p => p.id > 0, true);
                //组装插入数据
                var insertData = result.delivery_list.Select(item => new WeChatShippingDelivery() { deliveryId = item.delivery_id, deliveryName = item.delivery_name }).ToList();
                //更新数据库
                bl = await _dal.InsertAsync(insertData, true) > 0;

            }

            jm.data = result;

            jm.code = bl ? 0 : 1;
            jm.msg = bl ? "数据刷新成功" : "数据刷新失败";
            return jm;
        }

    }
}
